using DocumentManager.Models;
using Newtonsoft.Json;
using System.IO;

namespace DocumentManager.Services;

/// <summary>
/// 文档服务
/// </summary>
public class DocumentService
{
    private readonly JsonSerializerSettings _jsonSettings;

    public DocumentService()
    {
        _jsonSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            TypeNameHandling = TypeNameHandling.Auto,
            NullValueHandling = NullValueHandling.Ignore
        };
    }

    /// <summary>
    /// 保存文档到文件
    /// </summary>
    public async Task<bool> SaveDocumentAsync(Document document, string filePath)
    {
        try
        {
            // 更新文档路径和修改时间
            document.FilePath = filePath;
            document.ModifiedTime = DateTime.Now;

            // 序列化文档
            var json = JsonConvert.SerializeObject(document, _jsonSettings);
            
            // 写入文件
            await File.WriteAllTextAsync(filePath, json);
            
            // 标记为已保存
            document.HasUnsavedChanges = false;
            
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"保存文档失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 从文件加载文档
    /// </summary>
    public async Task<Document?> LoadDocumentAsync(string filePath)
    {
        try
        {
            if (!File.Exists(filePath))
                return null;

            // 读取文件内容
            var json = await File.ReadAllTextAsync(filePath);
            
            // 反序列化文档
            var document = JsonConvert.DeserializeObject<Document>(json, _jsonSettings);
            
            if (document != null)
            {
                document.FilePath = filePath;
                document.HasUnsavedChanges = false;
                
                // 重新设置父子关系
                SetupParentChildRelationships(document.RootNode);
                
                // 加载图片数据
                await LoadImageDataAsync(document);
            }
            
            return document;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"加载文档失败: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 创建新文档
    /// </summary>
    public Document CreateNewDocument(string title = "新建文档")
    {
        var document = new Document
        {
            Title = title,
            Author = Environment.UserName,
            CreatedTime = DateTime.Now,
            ModifiedTime = DateTime.Now
        };

        // 添加一个示例标题
        var titleNode = new DocumentNode
        {
            Title = "第一章",
            NodeType = DocumentNodeType.Title,
            Level = 1
        };
        
        document.RootNode.AddChild(titleNode);
        document.HasUnsavedChanges = false;

        return document;
    }

    /// <summary>
    /// 导出文档为JSON格式（用于调试）
    /// </summary>
    public string ExportToJson(Document document)
    {
        return JsonConvert.SerializeObject(document, _jsonSettings);
    }

    /// <summary>
    /// 获取文档的备份文件路径
    /// </summary>
    public string GetBackupFilePath(string originalPath)
    {
        var directory = Path.GetDirectoryName(originalPath) ?? "";
        var fileName = Path.GetFileNameWithoutExtension(originalPath);
        var extension = Path.GetExtension(originalPath);
        var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
        
        return Path.Combine(directory, $"{fileName}_backup_{timestamp}{extension}");
    }

    /// <summary>
    /// 创建文档备份
    /// </summary>
    public async Task<bool> CreateBackupAsync(Document document)
    {
        if (string.IsNullOrEmpty(document.FilePath))
            return false;

        try
        {
            var backupPath = GetBackupFilePath(document.FilePath);
            return await SaveDocumentAsync(document, backupPath);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"创建备份失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 设置父子关系（JSON反序列化后需要重新设置）
    /// </summary>
    private void SetupParentChildRelationships(DocumentNode node, DocumentNode? parent = null)
    {
        node.Parent = parent;
        
        foreach (var child in node.Children)
        {
            SetupParentChildRelationships(child, node);
        }
    }

    /// <summary>
    /// 加载图片数据
    /// </summary>
    private async Task LoadImageDataAsync(Document document)
    {
        var allNodes = document.GetAllNodes();
        var imageContents = allNodes.SelectMany(n => n.Contents.OfType<ImageContentItem>());

        foreach (var imageContent in imageContents)
        {
            // 从字节数组加载图片源
            imageContent.LoadImageFromData();
            
            // 如果有图片路径但没有数据，尝试从文件加载
            if (imageContent.ImageData == null && !string.IsNullOrEmpty(imageContent.ImagePath))
            {
                try
                {
                    if (File.Exists(imageContent.ImagePath))
                    {
                        imageContent.ImageData = await File.ReadAllBytesAsync(imageContent.ImagePath);
                        imageContent.LoadImageFromData();
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"加载图片文件失败: {ex.Message}");
                }
            }
        }
    }

    /// <summary>
    /// 验证文档完整性
    /// </summary>
    public DocumentValidationResult ValidateDocument(Document document)
    {
        var result = new DocumentValidationResult();
        
        try
        {
            // 检查基本信息
            if (string.IsNullOrWhiteSpace(document.Title))
                result.Warnings.Add("文档标题为空");
                
            if (string.IsNullOrWhiteSpace(document.Author))
                result.Warnings.Add("文档作者为空");

            // 检查节点结构
            var allNodes = document.GetAllNodes().ToList();
            var duplicateIds = allNodes.GroupBy(n => n.Id)
                                     .Where(g => g.Count() > 1)
                                     .Select(g => g.Key);
                                     
            foreach (var duplicateId in duplicateIds)
            {
                result.Errors.Add($"发现重复的节点ID: {duplicateId}");
            }

            // 检查图片内容
            var imageContents = allNodes.SelectMany(n => n.Contents.OfType<ImageContentItem>());
            foreach (var imageContent in imageContents)
            {
                if (imageContent.ImageData == null && string.IsNullOrEmpty(imageContent.ImagePath))
                {
                    result.Warnings.Add($"图片内容缺少数据: {imageContent.Id}");
                }
            }

            result.IsValid = result.Errors.Count == 0;
        }
        catch (Exception ex)
        {
            result.Errors.Add($"验证过程中发生错误: {ex.Message}");
            result.IsValid = false;
        }

        return result;
    }
}

/// <summary>
/// 文档验证结果
/// </summary>
public class DocumentValidationResult
{
    public bool IsValid { get; set; } = true;
    public List<string> Errors { get; set; } = new();
    public List<string> Warnings { get; set; } = new();
} 